<script>
import Vue from 'vue'
import * as api from '@/servies/request'
import i18n from '@/i18n'
import { Form } from 'ant-design-vue'
import FeatureForm from './FeatureForm.vue'
import BugForm from './BugForm.vue'
import PreviewModal from './PreviewModal.vue'
import createPreview from './createPreview.js'

Vue.use(i18n)
const params = location.search.slice(1).split('&').reduce((acc, param) => {
  const [key, value] = param.split('=');
  return { ...acc, [key]: value };
}, {});

if (!params.repo) {
  params.repo = 'ant-design-vue';
}

const BugReportForm = {
  data() {
    return {
      repoVersions: {},
      similarIssues: [],
      preview: false,
      reproModal: false,
    }
  },
  mounted() {
    this.fetchVerions(params.repo);
  },
  methods: {
    fetchVerions(repo) {
      api.fetchVersions(repo).then((versions) =>
        this.repoVersions = {
          ...this.repoVersions,
          [repo]: versions,
        },
      );
    },
    fetchIssues() {
      const { form } = this;
      const repo = form.getFieldValue('repo');
      const title = form.getFieldValue('title');
      if (title) {
        api
          .fetchIssues(repo, title)
          .then(issues => {
            this.similarIssues = issues
          });
      } else {
        this.similarIssues = []
      }
    },

    handleRepoChange(repo) {
      const { form } = this;
      form.resetFields(['version']);
      if (!this.repoVersions[repo]) {
        this.fetchVerions(repo);
      }
    },

    handleTitleBlur() {
      this.fetchIssues();
    },

    handlePreview(e) {
      e.preventDefault();
      this.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          this.preview = true
        }
      });
    },

    handleClosePreview() {
      this.preview = false
    },

    handleCreate() {
      const { form } = this;
      const issueType = form.getFieldValue('type');
      const repo = form.getFieldValue('repo');
      const title = encodeURIComponent(form.getFieldValue('title')).replace(
        /%2B/gi,
        '+',
      );
      const content = this.getContent(issueType);
      const withConfirm = `- [ ] I have searched the [issues](https://github.com/vueComponent/${repo}/issues) \
        of this repository and believe that this is not a duplicate.
        
        ${content}
        `;
            const withMarker = `${withConfirm}\n\n<!-- generated by issue-helper. DO NOT REMOVE -->`;
            const body = encodeURIComponent(withMarker).replace(/%2B/gi, '+');
            const label = issueType === 'feature' ? '&labels=Feature%20Request' : '';
            window.open(
              `https://github.com/vueComponent/${repo}/issues/new?title=${title}&body=${body}${label}`,
            );
    },

    getContent(issueType) {
      return createPreview(issueType, this.form.getFieldsValue());
    }
  },

  render() {
    const { form, similarIssues, repoVersions, preview } = this
    const { getFieldDecorator, getFieldValue } = form;
    const issueType = getFieldValue('type')
    const content = this.getContent(issueType)
    const repo = form.getFieldValue('repo')
    const versions = repoVersions[repo] || []

    const similarIssuesList = (
      <a-form-item>
        <h3>Similar Issues:</h3>
        <ul>
          {similarIssues.map(issue =>
            <li key={issue.id}>
              <a href={issue.html_url} target="_blank" rel="noreferer noopener">
                {issue.title}
              </a>
            </li>,
          )}
        </ul>
      </a-form-item>
    );

    return (
      <div class="bug-report" style="margin:0">
        <PreviewModal
          visible={preview}
          content={content}
          onCancel={this.handleClosePreview}
          onCreate={this.handleCreate}
        />
        <div class="vue-grid col-2 default-gap">
          <a-form layout="horizontal" onSubmit={this.handlePreview}>
            <a-form-item>
              <a-col span={11}>
                <a-form-item
                  label={this.i18n('issue.repo')}
                  help={this.i18n('issue.repoHelp')}
                >
                  {getFieldDecorator('repo', {
                    initialValue: params.repo,
                  })(
                    <a-select>
                      <a-select-option key="ant-design-vue">ant-design-vue</a-select-option>
                    </a-select>,
                  )}
                </a-form-item>
              </a-col>
              <a-col span={12} offset={1}>
                <a-form-item
                  label={this.i18n('issue.type')}
                >
                  {getFieldDecorator('type', {
                    initialValue: 'bug',
                  })(
                    <a-select>
                      <a-select-option key="bug">
                        {this.i18n('issue.type.bug')}
                      </a-select-option>
                      <a-select-option key="feature">
                        {this.i18n('issue.type.feature')}
                      </a-select-option>
                    </a-select>,
                  )}
                </a-form-item>
              </a-col>
            </a-form-item>
            <a-form-item
              label={this.i18n('issue.title')}
            >
              {getFieldDecorator('title', {
                rules: [{ required: true }],
              })(
                <a-input onBlur={this.handleTitleBlur} />
              )}
            </a-form-item>
            {similarIssues.length > 0 && similarIssuesList}
            {issueType !== 'feature' ? (
              <BugForm
                form={form}
                versions={versions}
                similarIssues={similarIssues}
              />
            ) : <FeatureForm form={form} />}
            <a-form-item>
              <div style={{marginTop: "20px",textAlign: "center"}}>
                <a-button type="primary" size="large" htmlType="submit">
                  {this.i18n('issue.preview')}
                </a-button>
              </div>
            </a-form-item>
          </a-form>
        </div>
      </div>
    )
  }
}

export default Form.create()(BugReportForm)
</script>
